package site.luojie.business.code.service;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import site.luojie.business.code.handler.MessageProducerHandler;
import site.luojie.business.code.mapper.AuthCodeMapper;
import site.luojie.business.code.pojo.AuthCode;
import site.luojie.common.vo.ResultVo;

import java.time.LocalDateTime;

/**
 * @author jie.luo
 * @since 2020/9/16
 */
@Service
public class CodeServiceImpl implements CodeService {

    @Autowired
    private MessageProducerHandler messageProducerHandler;
    @Autowired
    private AuthCodeMapper authCodeMapper;

    @Override
    public void sendVerifyCode(String email) {
        // 验证码
        String verifyCode = RandomStringUtils.randomNumeric(6);

        // 保存验证码
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(verifyCode);
        authCode.setCreateTime(LocalDateTime.now());
        authCode.setExpireTime(authCode.getCreateTime().plusMinutes(10));
        authCodeMapper.insertAuthCode(authCode);

        // 通过消息队列发送邮件
        messageProducerHandler.mqSendVerifyCode(email, verifyCode);
    }

    @Override
    public ResultVo<Boolean> verifyCodeCheck(String email, String verifyCode) {

        AuthCode authCode = authCodeMapper.selectLastAuthCode(email);
        if (null == authCode) {
            return ResultVo.customData("601", "未获取验证码");
        }

        if (LocalDateTime.now().isAfter(authCode.getExpireTime())) {
            return ResultVo.customData("602", "验证码已过期");
        }

        if (!verifyCode.equals(authCode.getCode())) {
            return ResultVo.customData("603", "验证码不匹配");
        }

        return ResultVo.ok();
    }
}
